<template>
  <div style="height: 100%" class="card">
    <el-form label-width="120px" style="width: 50%; margin-top: 20px">
      <el-form-item label="头像">

        <el-upload
            :action="uploadUrl()"
            :show-file-list="false"
            :on-success="setUserAvatar"
        >
          <el-avatar :size="80" :src="updateUserInfo.avatar">
          </el-avatar>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="updateUserInfo.nickName"/>
      </el-form-item>
      <el-form-item label="用户ID">
        <el-input v-model="updateUserInfo.userId" readonly/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveUserInfo">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {reactive} from "vue";
import {useLoginStore} from "@/store/index.js";
import {ElMessage} from "element-plus";
import AuthApi from "@/api/Auth.js";
import {uploadUrl} from "@/utils/Utils.js";

const {getUserLoginInfo, setLoginUserInfo} = useLoginStore()
const loginUserInfo = getUserLoginInfo()
const updateUserInfo = reactive({
  avatar: loginUserInfo.avatar,
  nickName: loginUserInfo.nickName,
  userId: loginUserInfo.userId
})

const saveUserInfo = () => {
  if (isBlank(updateUserInfo.userId)) {
    ElMessage.error("用户ID不能为空!")
    return
  }
  if (isBlank(updateUserInfo.avatar)) {
    ElMessage.error("头像不能为空!")
    return
  }
  if (isBlank(updateUserInfo.nickName)) {
    ElMessage.error("昵称不能为空!")
    return
  }
  AuthApi.updateUserProfile(updateUserInfo).then(res => {
    ElMessage.success("修改成功")
    AuthApi.getLoginUserInfo().then(res => {
      setLoginUserInfo(res.data)
    })
  })
}
const isBlank = (value) => {
  return value === null || value === "";
}
const setUserAvatar = (res) => {
  updateUserInfo.avatar = res.data.fileUrl
}
</script>

<style scoped>
.card {
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 0 12px rgba(0, 0, 0, 0.72);
}
</style>